<template>
  <div class="a3-page">
    <div class="tool-view">
      <div class="tool-l">
        <span>系统数据导入</span>
        <n-button color="#EE9708" @click="openFun(0)">导入</n-button>
        <span>手工数据导入</span>
        <n-button color="#EE9708" @click="openFun(1)">EXCLE导入</n-button>
        <span>时间刻度</span>
        <n-select
          placeholder="选择时间刻度"
          style="width: 120px"
          v-model:value="params.type"
          :options="options"
        />
        <span>时间筛选</span>
        <n-config-provider :locale="zhCN" :date-locale="dateZhCN">
          <n-date-picker
            style="width: 260px"
            v-model:value="range"
            :type="pickerType"
            clearable
            @update:formatted-value="timeChange"
            :is-date-disabled="disablePreviousDate"
          />
        </n-config-provider>
        <n-button
          style="margin-left: 12px"
          type="success"
          @click="GetProduceInfomationFun"
        >
          查询
        </n-button>
      </div>
      <div class="tool-r" @click="GetModelFileFun">
        <n-button color="#EE9708">模版下载</n-button>
      </div>
    </div>
    <div ref="container" class="table-view">
      <n-data-table
        remote
        :loading="loading"
        :data="data"
        :columns="columns"
        :single-line="false"
        :pagination="false"
        :scroll-x="scrollX"
        virtual-scroll
        :max-height="height"
        @update:page="handlePageChange"
      />
    </div>
  </div>
  <n-modal
    :mask-closable="false"
    class="edit-dialog"
    v-model:show="openDelDialog"
    :show-icon="false"
    preset="dialog"
    :on-close="closeWin"
    transform-origin="center"
    style="background: #60676c; height: 356px; width: 700px"
  >
    <template #header>
      <div class="title-font">
        {{ type === 0 ? "系统数据导入" : "手工数据导入" }}
      </div>
    </template>
    <div v-if="type === 0" class="notice-info">
      <div class="btn" @click="InsertProduceInfoFromMesFun">
        <icons class="icon" name="link" />
        <div class="text">自动导入</div>
      </div>
      <div class="btn t" @click="GetProduceInfoFromMesFun">
        <icons class="icon" name="hand" />
        <div class="text">手动导入</div>
      </div>
    </div>
    <div v-else class="notice-info">
      <div class="btn y">
        <input type="file" accept=".xlsx, .xls" @change="handleFileUpload" />
        <icons class="icon" name="edit" />
        <div class="text">EXCEL导入</div>
      </div>
      <div class="btn t" @click="openHandWin">
        <icons class="icon" name="hand" />
        <div class="text">手动写入</div>
      </div>
    </div>
  </n-modal>
  <n-modal
    :mask-closable="false"
    class="edit-dialog"
    v-model:show="openPlan"
    :show-icon="false"
    preset="dialog"
    :on-close="closeWin"
    transform-origin="center"
    style="background: #60676c; width: 700px"
  >
    <template #header>
      <div class="title-font">手工写入</div>
    </template>
    <div class="notice-info">
      <div class="form-view">
        <div v-for="(item, i) in dataList" :key="i" class="line">
          <div class="form-item">
            <div class="line-view">
              产品名称
              <n-input
                v-model:value="item.productName"
                type="text"
                class="input"
                placeholder="输入产品名称"
              />
            </div>
            <div class="line-view">
              计划数量
              <n-input
                type="text"
                class="input"
                v-model:value="item.plannedQuantity"
                :allow-input="onlyAllowNumber"
                placeholder="输入数量"
              />
            </div>
            <div
              v-if="dataList.length > 1"
              class="del-btn"
              @click="delPlanItem(i)"
            >
              <icons class="icon" name="delete" />
            </div>
            <div v-else class="del-btn"></div>
          </div>
          <div class="form-item">
            <div class="line-view">
              开始时间
              <n-config-provider :locale="zhCN" :date-locale="dateZhCN">
                <n-date-picker
                  class="picker"
                  @update:formatted-value="(d: string) => (item.startTime = d)"
                  type="date"
                  :is-date-disabled="disablePreviousDate"
                />
              </n-config-provider>
            </div>
            <div class="line-view">
              结束时间
              <n-config-provider :locale="zhCN" :date-locale="dateZhCN">
                <n-date-picker
                  class="picker"
                  @update:formatted-value="(d: string) => (item.endTime = d)"
                  type="date"
                  :is-date-disabled="disablePreviousDate"
                />
              </n-config-provider>
            </div>
            <div class="del-btn"></div>
          </div>
        </div>
        <div class="add-plan" @click="addPlanItem">
          <icons class="icon" name="add" />添加计划
        </div>
        <div class="null" style="min-height: 100px"></div>
      </div>
    </div>
    <div class="footer-view">
      <n-button class="btn" ghost @click="closeWin"> 取消 </n-button>
      <n-button class="btn" color="#01C0E4" @click="InsertProduceInfomationFun">
        保存
      </n-button>
    </div>
  </n-modal>
  <n-modal
    :mask-closable="false"
    class="edit-dialog"
    v-model:show="openSecond"
    :show-icon="false"
    preset="dialog"
    :on-close="closeWin"
    transform-origin="center"
    style="background: #60676c; width: 700px"
  >
    <template #header>
      <div class="title-font">人工确认</div>
    </template>
    <div class="notice-info">
      <div class="form-view">
        <div v-for="(item, i) in dataList" :key="i" class="line">
          <div class="form-item">
            <div class="line-view">
              产品名称
              <n-input
                read-only
                v-model:value="item.productName"
                type="text"
                class="input"
                placeholder="输入产品名称"
              />
            </div>
            <div class="line-view">
              计划数量
              <n-input
                read-only
                type="text"
                v-model:value="item.plannedQuantity"
                class="input"
                :allow-input="onlyAllowNumber"
                placeholder="输入数量"
              />
            </div>
          </div>
          <div class="form-item">
            <div class="line-view">
              开始时间
              <n-input
                read-only
                v-model:value="item.startTime"
                type="text"
                class="input"
                placeholder="输入产品名称"
              />
            </div>
            <div class="line-view">
              结束时间
              <n-input
                read-only
                v-model:value="item.endTime"
                type="text"
                class="input"
                placeholder="输入产品名称"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="footer-view">
      <n-button class="btn" ghost @click="closeWin"> 取消 </n-button>
      <n-button class="btn" color="#01C0E4" @click="InsertProduceInfomationFun">
        确认
      </n-button>
    </div>
  </n-modal>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { zhCN, dateZhCN } from "naive-ui";
import {
  GetProduceInfomation,
  InsertProduceInfoFromMes,
  GetProduceInfoFromMes,
  GetModelFile,
  UploadExcelFile,
  InsertProduceInfomationByExcel,
  InsertProduceInfomation,
} from "@/server";
import { today } from "@/tools/radom";
import { useAppStore } from "@/store/modules/user";
const route = useRoute();
const modelId = computed(() => route.params.id);
const store = useAppStore();
const data = ref([]) as any;
const columns = ref([]) as any;
const loading = ref(false);
const openPlan = ref(false);
const openSecond = ref(false);
const openDelDialog = ref(false);
const defalutData = {
  productName: "",
  plannedQuantity: "",
  startTime: Date.now(),
  endTime: Date.now(),
};
const dataList = ref([]) as any; //手动添加数据
const range = ref<[number, number]>([Date.now(), Date.now()]);
const options = [
  {
    label: "天",
    value: "天",
  },
  {
    label: "月",
    value: "月",
  },
  {
    label: "年",
    value: "年",
  },
];
const scrollX = ref(1400);
const type = ref(0);
const pickerType = computed(() => {
  if (params.value.type === "天") {
    return "daterange";
  } else if (params.value.type === "月") {
    return "monthrange";
  } else {
    return "yearrange";
  }
});
const params = ref({
  type: "天",
  startTime: today(),
  endTime: today(),
}) as any;
const timeChange = (e: any) => {
  params.value.startTime = e[0];
  params.value.endTime = e[1];
};
const handlePageChange = (curent: number) => {
  console.log(curent);
  GetProduceInfomationFun();
};
watch(
  () => modelId.value,
  () => {
    GetProduceInfomationFun();
  }
);
const closeWin = () => {
  openSecond.value = false;
  openPlan.value = false;
  openDelDialog.value = false;
};
const openFun = (n: number) => {
  type.value = n;
  openDelDialog.value = true;
};
const addPlanItem = () => {
  dataList.value.push(JSON.parse(JSON.stringify(defalutData)));
};
const delPlanItem = (i: number) => {
  dataList.value.splice(i, 1);
};
const openHandWin = () => {
  dataList.value = [JSON.parse(JSON.stringify(defalutData))];
  openPlan.value = true;
};
const lock = ref(false);
const unLock = () => {
  setTimeout(() => {
    lock.value = false;
  }, 1000);
};
const disablePreviousDate = (ts: number) => {
  return ts > Date.now();
};
//获取初始化数据
const GetProduceInfomationFun = async () => {
  loading.value = true;
  if (lock.value) {
    return false;
  }
  lock.value = true;
  const res: any = await GetProduceInfomation(params.value);
  if (res.result.isSuccess) {
    loading.value = false;
    unLock();
    createData(res.result.result);
  } else {
    unLock();
    loading.value = false;
    store.error(res.result.message); // 错误提示
  }
};
GetProduceInfomationFun();
const container = ref(null) as any;
const height = ref(0);
const updateHeight = () => {
  const containerHeight = container.value.offsetHeight;
  console.log("Container Height:", containerHeight);
  height.value = containerHeight - 120;
};
onMounted(() => {
  updateHeight();
  window.addEventListener("resize", updateHeight);

  // Cleanup listener on component unmount
  return () => {
    window.removeEventListener("resize", updateHeight);
  };
});
const onlyAllowNumber = (value: string) => !value || /^\d+$/.test(value);
function createData(arr: any) {
  const colList: any = [
    {
      title: "OPX",
      key: "station",
      width: 120,
      fixed: "left",
      algin: "center",
      titleAlign: "center",
    },
    {
      title: "任务",
      key: "task",
      width: 120,
      fixed: "left",
      algin: "center",
      titleAlign: "center",
    },
    {
      title: "产品名称",
      width: 120,
      key: "productName",
      fixed: "left",
      algin: "center",
      titleAlign: "center",
    },
  ];

  const list: any = [];
  for (let index = 0; index < arr.length; index++) {
    const element = arr[index];
    const plan = element.produceTask.plan;
    const completed = element.produceTask.completed;
    const Qualified = element.produceTask.qualified;
    const Defective = element.produceTask.defective;
    const planData: any = {
      key: list.length,
      station: element.station,
      productName: element.productName,
    };
    let unit = "";
    if (params.value.type === "天") {
      unit = "午";
    } else if (params.value.type === "月") {
      unit = "半月";
    } else {
      unit = "半年";
    }
    for (let k = 0; k < plan.length; k++) {
      const task = plan[k];
      const findIndex = colList.findIndex((e: any) => e.title === task.time);
      if (findIndex === -1) {
        colList.push({
          title: task.time,
          key: "time",
          algin: "center",
          titleAlign: "center",
          width: 140,
          children: [
            {
              title: "上" + unit,
              key: [task.time + "firstHalf"],
              algin: "center",
              titleAlign: "center",
            },
            {
              title: "下" + unit,
              key: [task.time + "secondHalf"],
              algin: "center",
              titleAlign: "center",
            },
          ],
        });
      }
      planData.task = "计划中";
      planData[task.time + "firstHalf"] = task.firstHalf;
      planData[task.time + "secondHalf"] = task.secondHalf;
    }
    list.push(planData);
    const completedData: any = {
      key: list.length,
      opx: "",
      name: "",
    };
    for (let k = 0; k < completed.length; k++) {
      const task = completed[k];
      completedData.task = "已完成";
      completedData[task.time + "firstHalf"] = task.firstHalf;
      completedData[task.time + "secondHalf"] = task.secondHalf;
    }
    list.push(completedData);
    const QualifiedData: any = {
      key: list.length,
      opx: "",
      name: "",
    };
    for (let k = 0; k < Qualified.length; k++) {
      const task = Qualified[k];
      QualifiedData.task = "已完成合格品";
      QualifiedData[task.time + "firstHalf"] = task.firstHalf;
      QualifiedData[task.time + "secondHalf"] = task.secondHalf;
    }
    list.push(QualifiedData);
    const DefectiveData: any = {
      key: list.length,
      opx: "",
      name: "",
    };
    for (let k = 0; k < Defective.length; k++) {
      const task = Defective[k];
      DefectiveData.task = "已完成瑕疵品";
      DefectiveData[task.time + "firstHalf"] = task.firstHalf;
      DefectiveData[task.time + "secondHalf"] = task.secondHalf;
    }
    list.push(DefectiveData);
  }
  data.value = list;
  scrollX.value = colList.length * 140 - 180;
  columns.value = colList;
}
async function downloadXLSX(url: string) {
  console.log(url);
  let fileName = url.slice(url.lastIndexOf("/") + 1); // 这里是通过从后端获取到的 url  地址中截出来原本的文件名
  const link = document.createElement("a");
  link.href = url;
  // 下载文件的名称及文件类型后缀
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  //在资源下载完成后 清除 占用的缓存资源
  window.URL.revokeObjectURL(link.href);
  document.body.removeChild(link);
}
//获取模版
const GetModelFileFun = async () => {
  const res: any = await GetModelFile({});
  if (res.result.isSuccess) {
    downloadXLSX(res.result.result);
    // dataList.value = res.result.result;
    // openSecond.value = true;
    // store.success(res.result.message); // 错误提示
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//手动导入获取数据
const GetProduceInfoFromMesFun = async () => {
  const res: any = await GetProduceInfoFromMes({});
  if (res.result.isSuccess) {
    dataList.value = res.result.result;
    openSecond.value = true;
    // store.success(res.result.message); // 错误提示
  } else {
    store.error(res.result.message); // 错误提示
  }
};
const handDatList = ref([]) as any;
//自动导入数据
const InsertProduceInfoFromMesFun = async () => {
  const res: any = await InsertProduceInfoFromMes([]);
  if (res.result.isSuccess) {
    store.success(res.result.message); // 错误提示
  } else {
    store.error(res.result.message); // 错误提示
  }
};
/**
 * @description: 上传文件
 * @param {*} event
 * @return {*}
 * @author: cool panda
 */
const handleFileUpload = async (event: any) => {
  const file = event.target.files[0];
  const fd = new FormData();
  fd.append("file", file);
  const res: any = await UploadExcelFile(fd);
  if (res.result.isSuccess) {
    const filePath = res.result.result.filePath; //图片上传的路径
    InsertProduceInfomationByExcelFun(filePath);
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//上传excle文件
const InsertProduceInfomationByExcelFun = async (filePath: string) => {
  const res: any = await InsertProduceInfomationByExcel({ path: filePath });
  if (res.result.isSuccess) {
    store.success(res.result.message); // 错误提示
  } else {
    store.error(res.result.message); // 错误提示
  }
};
// 手动添加数据
const InsertProduceInfomationFun = async () => {
  const filterList = dataList.value.filter(
    (e: any) =>
      !e.productName || !e.plannedQuantity || !e.startTime || !e.endTime
  );
  if (filterList.length > 0) {
    store.warning("请完善信息"); // 错误提示
    return false;
  }
  const res: any = await InsertProduceInfomation(dataList.value);
  if (res.result.isSuccess) {
    dataList.value = [];
    store.success(res.result.message); // 错误提示
    closeWin();
  } else {
    store.error(res.result.message); // 错误提示
  }
};
</script>

<style lang="less" scoped>
.a3-page {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background: #ffffff;
  overflow: hidden;

  .tool-view {
    display: flex;
    height: 60px;
    align-items: center;
    justify-content: space-between;
    background: #e3e3e3;
    backdrop-filter: blur(32px);

    .tool-l {
      display: flex;
      align-items: center;
      flex: 1;

      span {
        font-size: 18px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        color: #1c262d;
        line-height: 25px;
        margin: 0 12px 0 28px;
      }
    }

    .tool-r {
      padding-right: 30px;
    }
  }

  .table-view {
    padding: 0 10px;
    height: calc(100% - 60px);
  }
}

:deep(.n-data-table-td) {
  text-align: center;
}

// :deep(.n-data-table-th) {
//   min-width: 60px;
//   width: 140px;
// }

.edit-dialog {
  .title-font {
    font-size: 24px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    color: #02a8ae;
    line-height: 35px;
  }

  .notice-info {
    padding: 40px 0;
    display: flex;
    justify-content: space-around;

    .btn {
      position: relative;

      &:hover {
        opacity: 1;
      }

      opacity: 0.8;
      cursor: pointer;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      &.t {
        background: #02a8ae;
      }

      &.y {
        background: #ee9708;

        input {
          opacity: 0;
          position: absolute;
          width: 100%;
          height: 100%;
          top: 0;
          left: 0;
        }
      }

      width: 200px;
      height: 200px;
      background: #01c0e4;
      box-shadow: 0px 0px 1px 0px rgba(0, 0, 0, 0.08),
        0px 1px 3px 0px rgba(25, 15, 15, 0.07),
        0px 3px 5px 0px rgba(0, 0, 0, 0.05);

      .icon {
        width: 76px;
        height: 76px;
      }

      .text {
        margin-top: 6px;
        font-size: 16px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        color: #ffffff;
        line-height: 29px;
      }
    }

    .form-view {
      width: 100%;
      padding: 0 30px;

      .add-plan {
        cursor: pointer;
        width: 130px;
        margin-top: 20px;
        display: flex;
        align-items: center;

        .icon {
          width: 30px;
          height: 30px;
          margin-right: 8px;
        }

        font-size: 16px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        color: #ee9708;
        line-height: 22px;
      }

      .line {
        border-bottom: 1px dashed rgba(247, 247, 247, 0.3);
        margin-bottom: 15px;
      }

      .form-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        .del-btn {
          cursor: pointer;
          display: flex;
          justify-content: center;
          align-items: center;
          width: 30px;
          height: 30px;

          .icon {
            width: 20px;
            height: 20px;
          }
        }

        .line-view {
          display: flex;
          align-items: center;
          font-size: 16px;
          font-family: PingFangSC, PingFang SC;
          font-weight: 500;
          color: #ffffff;
          line-height: 22px;

          .input {
            width: 180px;
            margin-left: 10px;
          }

          :deep(.n-input) {
            background: none;

            input {
              height: 36px;
              color: #ffffff;
            }
          }

          .picker {
            color: #ffffff;
            background: none;
            margin-left: 10px;
            width: 180px;
          }
        }
      }
    }
  }

  .footer-view {
    width: 100%;
    display: flex;
    justify-content: center;
    position: absolute;
    bottom: 0px;

    .btn {
      width: 100px;
      margin: 0 10px;
      color: #ffffff;
    }
  }
}

// :deep(.n-data-table-th__title) {
//   text-align: center;
// }
</style>
